package net.es.weathermap {
public class Vector2D {

    private var _x:Number;
    private var _y:Number;
    private var length:Number;


    function Vector2D (x:Number, y:Number)
    {
        this._x = x || 0;
        this._y = y || 0;
        this.length = Math.sqrt(this._x * this._x + this._y * this._y);
    }


    public function getx():Number
    {
        return this._x;
    }


    public function gety():Number
    {
        return this._y;
    }


    public function getlength():Number
    {
        return Math.sqrt(this._x * this._x + this._y * this._y);
    }


    public static function interpolate(pt1:Vector2D, pt2:Vector2D, f:Number):Vector2D
    {
        return new Vector2D(f * pt1._x + (1 - f) * pt2._x, f * pt1._y + (1 - f) * pt2._y);
    }

    public static function scale(a:Vector2D, f:Number):Vector2D {
    	return new Vector2D(f * a._x, f * a._y);
    }
    public static function distance(a:Vector2D, b:Vector2D):Number
    {
        var dx:Number = b._x - a._x;
        var dy:Number = b._y - a._y;

        return Math.sqrt(dx * dx + dy * dy);
    }


    public static function polar(len:Number, angle:Number):Vector2D
    {
        return new Vector2D(len * Math.cos(angle), len * Math.sin(angle));
    }


    public function clone():Vector2D
    {
        return new Vector2D(this._x, this._y);
    }


    public function offset(dx:Number, dy:Number):void
    {
        this._x += dx;
        this._y += dy;
    }


    public function equals(toCompare:Object):Boolean {
    //  slower!
    //  return ((toCompare instanceof Vector2D) && (toCompare._x == this._x) && (toCompare._y == this._y));

    //  faster!
        if (!(toCompare is Vector2D))
        {
            return false;
        }
        if  (toCompare._x != this._x)
        {
            return false;
        }
        if (toCompare._y != this._y)
        {
            return false;
        }
        return true;
    }


    public function subtract(other:Vector2D):Vector2D
    {
        var p:Vector2D = new Vector2D(this._x, this._y);
        p._x -= other._x;
        p._y -= other._y;
        return p;
    }


    public function add(other:Vector2D):Vector2D
    {
        var p:Vector2D = new Vector2D(this._x, this._y);
        p._x += other._x;
        p._y += other._y;
        return p;
    }


    public function normalize(length:Number):void
    {
        var l:Number = this.length;
        if (l > 0)
        {
            var factor:Number = length/l;
            this._x *= factor;
            this._y *= factor;
        }
    }


    public function toString():String
    {
        return ("(x=" + this._x + ", y=" + this._y + ")");
    }


}
}
